<?php

require_once 'utils/JsonUtils.php';

/**
 * Description of GameResource
 *
 * @uri /game
 * @author alexey.ogarkov
 */
class GameResource extends Resource{
    
    public function post(Request $request) {
        $response = new Response($request);
        
        $game = json_decode($request->data);               
        
        //Need to validate new game
        $user_id = $game->user_id;
        $game_type = $game->online;
        
        if (null == $user_id || !is_numeric($user_id)) {
            $response->code = Response::NOTACCEPTABLE;                    
            return $response;
        }
        
        try {        
            $player = EntityManagerFactory::getEntityManager()->getRepository("Player")->findPlayerByFacebookId($user_id);
        } catch (Doctrine\ORM\NoResultException $ex) {
            EntityManagerFactory::getEntityManager()->getRepository("Player")->createPlayer($user_id,"Dummy Name");
            $player = EntityManagerFactory::getEntityManager()->getRepository("Player")->findPlayerByFacebookId($user_id);
        }                      
        
        $created_game = EntityManagerFactory::getEntityManager()->getRepository("Game")->createGame($player,$game);
        $response_game = array('game_id'=>$created_game->getId(), "game_hash" => $created_game->getUpdateHash(),"update_date" => $created_game->getUpdateDate());
        
        $response->code = Response::CREATED;
        $response->headers["Content-Type"] = "application/json";
        $response->body = json_encode($response_game);
        return $response;        
    }
}

?>
